# encoding: utf-8
from app.extensions import log, db
from flask_restplus import Resource
from app.extensions.api import Namespace
from . import schemas, parameters
from flask_restplus_patched import Parameters
from app.modules.common.schemas import BaseSchema
from .models import App
from app.modules.common.utils import DbCommit, checkToken
from app.modules.zone.models import Zone

api = Namespace('app', description = "应用记录")  # pylint: disable=invalid-name


@api.route('/')
class List(Resource):
    @api.parameters(Parameters())
    @api.response(schemas.AppListSchema(many = False))
    def get(self, args, **kwargs):
        """
        查询应用列表，同步用
        :param args:
        :return:
        """
        log.info("============== start get app list ==============")
        _list = App.query.all()
        return {'success': True, 'msg': '', 'data': _list}


@api.route('/add')
class AddApp(Resource):
    @api.parameters(parameters.AppAddParameters())
    @api.response(BaseSchema(many = False))
    @checkToken
    def post(self, args, **kwargs):
        """
        添加app
        :param args:
        :return:
        """
        log.info("============== start add app ==============")
        _app_id = args['app_id']
        _app_name = args['app_name']
        _port = args['port']
        _zone_code = args['zone_code']
        _db_type = args['db_type']
        _db_name = args['db_name']
        _app_type = args['app_type']
        _on_beetle = args['on_beetle']
        _starting_order = args['starting_order']
        _zone = Zone.query.filter_by(zone_code = _zone_code).first()
        if _zone is None:
            _msg = '区域 %s 不存在' % _zone_code
            log.error('============== %s ==============' % _msg)
            return {'success': False, 'msg': _msg}

        _app = App.query.filter_by(app_id = _app_id).first()
        if _app is not None:
            _msg = '应用 %s 已存在' % _app_id
            log.error('============== %s ==============' % _msg)
            return {'success': False, 'msg': _msg}

        _app = App.query.filter_by(port = _port).first()
        if _app is not None:
            _msg = '端口 %s 已被占用' % _port
            log.error('============== %s ==============' % _msg)
            return {'success': False, 'msg': _msg}

        _app = App(app_id = _app_id, zone_code = _zone_code, app_name = _app_name, port = _port, app_type = _app_type,
                   db_name = _db_name, db_type = _db_type, status = 'unavailable', version = '-1',
                   on_beetle = _on_beetle, db_status = 'unavailable', starting_order = _starting_order)
        db.session.add(_app)
        return DbCommit()
